package com.cx.base.day18_jdk8新特性;

import com.cx.base.day13_io.io_05_objectStream.Person;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @Author: robert.song
 * @Date: Created in 2021/12/20
 */
public class StreamExamle {
    public static void main(String[] args) {
        way3();
    }

    //  遍历/匹配（foreach/find/match）
    public static void way1() {
        List<Integer> list = Arrays.asList(31, 7, 6, 9, 3, 8, 2, 1);
        // 遍历输出符合条件的元素
        list.stream().filter(x -> x > 6).forEach(System.out::println);
        // 匹配第一个
        Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
        // 匹配任意（适用于并行流）
        Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
        // 是否包含符合特定条件的元素
        boolean anyMatch = list.stream().anyMatch(x -> x > 6);
        System.out.println("匹配第一个值：" + findFirst.get());
        System.out.println("匹配任意一个值：" + findAny.get());
        System.out.println("是否存在大于6的值：" + anyMatch);
    }

    //  筛选（filter）
    public static void way2() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 21));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));

        List<String> fiterList = personList.stream().filter(x -> x.getAge() > 23).map(Person::getName)
                .collect(Collectors.toList());
        System.out.print("高于23的员工姓名：" + fiterList);
    }

    //    聚合（max/min/count)
    public static void way3() {
//        字符串最大值
        List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");

        Optional<String> max = list.stream().max(Comparator.comparing(String::length));
        System.out.println("最长的字符串：" + max.get());

//        整型最大值
        List<Integer> list1 = Arrays.asList(7, 6, 9, 4, 11, 6);

        // 自然排序
        Optional<Integer> max1 = list1.stream().max(Integer::compareTo);
        // 自定义排序
        Optional<Integer> max2 = list1.stream().max(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        System.out.println("自然排序的最大值：" + max1.get());
        System.out.println("自定义排序的最大值：" + max2.get());
        System.out.println(list1.stream().filter(x -> x > 7).count());
    }

    // 映射(map/flatMap)
    public static void way4() {
        String[] strArr = {"abcd", "bcdd", "defde", "fTr"};
        List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("每个元素大写：" + strList);

        List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
        List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList());
        System.out.println("每个元素+3：" + intListNew);

        List<String> list = new ArrayList<>();
        list.add("aaa bbb ccc");
        list.add("ddd eee fff");
        list.add("ggg hhh iii");
        list = list.stream().map(s -> s.split(" ")).flatMap(Arrays::stream).collect(Collectors.toList());
        System.out.println(list);
    }

    //    排序(sorted)
    public static void way5() {
        List<Person> personList = new ArrayList<Person>();

        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 21));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));

        // 按工资升序排序（自然排序）
        List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getAge)).map(Person::getName)
                .collect(Collectors.toList());
        // 按工资倒序排序
        List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getAge).reversed())
                .map(Person::getName).collect(Collectors.toList());
        // 先按工资再按年龄升序排序
        List<String> newList3 = personList.stream()
                .sorted(Comparator.comparing(Person::getAge).thenComparing(Person::getAge)).map(Person::getName)
                .collect(Collectors.toList());
        // 先按工资再按年龄自定义排序（降序）
        List<String> newList4 = personList.stream().sorted((p1, p2) -> {
            if (p1.getAge() == p2.getAge()) {
                return p2.getAge() - p1.getAge();
            } else {
                return p2.getAge() - p1.getAge();
            }
        }).map(Person::getName).collect(Collectors.toList());

        System.out.println("按工资升序排序：" + newList);
        System.out.println("按工资降序排序：" + newList2);
        System.out.println("先按工资再按年龄升序排序：" + newList3);
        System.out.println("先按工资再按年龄自定义降序排序：" + newList4);
    }

    //    提取/组合
    public static void way6() {
        String[] arr1 = {"a", "b", "c", "d"};
        String[] arr2 = {"d", "e", "f", "g"};

        Stream<String> stream1 = Stream.of(arr1);
        Stream<String> stream2 = Stream.of(arr2);
        // concat:合并两个流 distinct：去重
        List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
        // limit：限制从流中获得前n个数据
        List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
        // skip：跳过前n个数据
        List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

        System.out.println("流合并：" + newList);
        System.out.println("limit：" + collect);
        System.out.println("skip：" + collect2);
    }

    //    规约 reduce
    public static void way11() {
        List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
        // 求和方式1
        Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
        // 求和方式2
        Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
        // 求和方式3
        Integer sum3 = list.stream().reduce(0, Integer::sum);

        // 求乘积
        Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

        // 求最大值方式1
        Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
        // 求最大值写法2
        Integer max2 = list.stream().reduce(1, Integer::max);

        System.out.println("list求和：" + sum.get() + "," + sum2.get() + "," + sum3);
        System.out.println("list求积：" + product.get());
        System.out.println("list求和：" + max.get() + "," + max2);
    }

    //    收集
//    归集（toList/toSet/toMap）
    public static void collect_way7() {
        List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
        List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
        Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());

        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 22));
        personList.add(new Person("Jack", 23));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));
        personList.add(new Person("Alisa", 24));
        personList.add(new Person("Owen", 25));

        Map<?, Person> map = personList.stream().filter(p -> p.getAge() > 23)
                .collect(Collectors.toMap(Person::getName, p -> p));
        System.out.println("toList:" + listNew);
        System.out.println("toSet:" + set);
        System.out.println("toMap:" + map);
    }

    //    统计（count、averaging）
    public static void collect_way12() {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 22));
        personList.add(new Person("Jack", 23));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));
        personList.add(new Person("Alisa", 24));
        personList.add(new Person("Owen", 25));

        // 求总数
        Long count = personList.stream().collect(Collectors.counting());
        // 求平均年龄
        Double average = personList.stream().collect(Collectors.averagingDouble(Person::getAge));
        // 求最高年龄
        Optional<Integer> max = personList.stream().map(Person::getAge).collect(Collectors.maxBy(Integer::compare));
        // 求年龄之和
        Integer sum = personList.stream().collect(Collectors.summingInt(Person::getAge));
        // 一次性统计所有信息
        DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getAge));

        System.out.println("员工总数：" + count);
        System.out.println("员工平均年龄：" + average);
        System.out.println("员工最大年龄：" + max.get());
        System.out.println("员工年龄总和：" + sum);
        System.out.println("员工年龄所有统计：" + collect);
    }

    //    分组(partitioningBy/groupingBy)
    public static void collect_way10() {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 22));
        personList.add(new Person("Jack", 23));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));
        personList.add(new Person("Alisa", 24));
        personList.add(new Person("Owen", 25));

        // 将员工按年龄>23分组
        Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 23));
        // 将员工按性别分组
        Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getName));
        // 将员工先按年龄分组，再按姓名分组
        Map<Integer, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(Person::getName)));
        System.out.println("员工按年龄>23分组情况：");
        part.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
        System.out.println("员工按姓名分组情况：");
        group.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
        System.out.println("员工按姓名、年龄分组情况：");
        group2.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
    }

    //    连接 joining
    public static void collect_way9() {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 21));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));

        String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
        System.out.println("所有员工的姓名：" + names);
        List<String> list = Arrays.asList("A", "B", "C");
        String string = list.stream().collect(Collectors.joining("-"));
        System.out.println("拼接后的字符串：" + string);
    }

    //    规约（reducing）
    public static void collect_way8() {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 23));
        personList.add(new Person("Jack", 25));
        personList.add(new Person("Lily", 21));
        personList.add(new Person("Anni", 24));
        personList.add(new Person("Owen", 23));
        personList.add(new Person("Alisa", 23));

        // 每个员工减去起征点后的薪资之和（这个例子并不严谨，但一时没想到好的例子）
        Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getAge, (i, j) -> (i + j - 5000)));
        System.out.println("员工扣税薪资总和：" + sum);

        // stream的reduce
        Optional<Integer> sum2 = personList.stream().map(Person::getAge).reduce(Integer::sum);
        System.out.println("员工薪资总和：" + sum2.get());
    }
}
